<template>
  <div class="app-container">
    <!-- 查询 -->
    <Search :name="name" :idkey="idkey" :basedata="basedata" @search="search" @reset="reset" />
    <!-- 操作 -->
    <Operate :name="name" :ids="ids" :basedata="basedata" :query="query" @list="list" @add="add" @edit="edit" />
    <!-- 列表 -->
    <el-row class="mt-2">
      <el-col :span="4">
        <el-row>
          <el-col>
            <el-text size="default" class="cursor-pointer" @click="deptSelect(null)">
              {{ $t('部门') }}：
              <Icons icon="RefreshLeft" />
            </el-text>
          </el-col>
          <el-col>
            <el-tree-v2
              ref="deptRef"
              :data="basedata.depts"
              :props="basedata.deptProps"
              :current-node-key="query.dept_id"
              highlight-current
              @node-click="deptSelect"
            />
          </el-col>
          <el-col class="pt-4">
            <el-text size="default" class="cursor-pointer" @click="postSelect(null)">
              {{ $t('职位') }}：
              <Icons icon="RefreshLeft" />
            </el-text>
          </el-col>
          <el-col>
            <el-tree-v2
              ref="postRef"
              :data="basedata.posts"
              :props="basedata.postProps"
              :current-node-key="query.post_id"
              highlight-current
              @node-click="postSelect"
            />
          </el-col>
          <el-col class="pt-4">
            <el-text size="default" class="cursor-pointer" @click="roleSelect(null)">
              {{ $t('角色') }}：
              <Icons icon="RefreshLeft" />
            </el-text>
          </el-col>
          <el-col>
            <el-tree-v2
              ref="roleRef"
              :data="basedata.roles"
              :props="basedata.roleProps"
              :current-node-key="query.role_id"
              highlight-current
              @node-click="roleSelect"
            />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="20">
        <el-table
          ref="table"
          v-loading="loading"
          :data="data"
          :height="height"
          show-overflow-tooltip
          @sort-change="sort"
          @selection-change="select"
        >
          <el-table-column type="selection" width="42" :title="$t('全选/反选')" />
          <el-table-column :prop="idkey" label="ID" width="80" sortable="custom" />
          <el-table-column prop="avatar_id" :label="$t('头像')" min-width="68">
            <template #default="{ row }">
              <FileImage :file-url="row.avatar_url" avatar lazy />
            </template>
          </el-table-column>
          <el-table-column prop="unique" :label="$t('编号')" min-width="100" sortable="custom" />
          <el-table-column prop="nickname" :label="$t('昵称')" min-width="100" sortable="custom" />
          <el-table-column prop="username" :label="$t('账号')" min-width="100" sortable="custom" />
          <el-table-column prop="dept_names" :label="$t('部门')" min-width="120" />
          <el-table-column prop="post_names" :label="$t('职位')" min-width="120" />
          <el-table-column prop="role_names" :label="$t('角色')" min-width="120" />
          <el-table-column
            prop="is_super_name"
            :label="$t('超管')"
            min-width="80"
            sortable="custom"
            column-key="is_super"
          />
          <el-table-column prop="remark" :label="$t('备注')" min-width="130" />
          <el-table-column
            prop="is_disable_name"
            :label="$t('禁用')"
            min-width="80"
            sortable="custom"
            column-key="is_disable"
          />
          <el-table-column prop="sort" :label="$t('排序')" min-width="80" sortable="custom" />
          <el-table-column :label="$t('操作')" width="110">
            <template #default="{ row }">
              <ElLinkOperate v-if="hasPerm([permEdit])" :text="$t('修改')" @click="edit(row)" />
              <ElLinkOperate v-else-if="hasPerm([permInfo])" :text="$t('信息')" @click="edit(row)" />
              <ElLinkOperate v-if="hasPerm([permDele])" :text="$t('删除')" @click="dele(row)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row class="mt-5 ml-3">
          <el-col :span="3">
            <el-checkbox v-model="addEditDialog" class="pr-6" :title="$t('添加修改时是弹窗还是新标签页')">
              <el-text size="default">{{ $t('弹窗') }}</el-text>
            </el-checkbox>
          </el-col>
          <el-col :span="21">
            <Pagination
              v-model:total="count"
              v-model:page="query.page"
              v-model:limit="query.limit"
              @pagination="list"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!-- 添加修改 -->
    <el-dialog
      v-model="dialog"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cancel"
      destroy-on-close
      append-to-body
      draggable
      align-center
      center
    >
      <AddEdit :id="id" :type="type" dialog @close="close" />
    </el-dialog>
  </div>
</template>

<script>
import Search from './component/Search.vue'
import Operate from './component/Operate.vue'
import AddEdit from './component/AddEdit.vue'
import { hasPerm, screenHeight, arrayColumn, getAddEditDialog, getChildIds } from '@/utils/index'
import { listApi, deleApi } from '@/api/system/user'

export default {
  name: 'SystemUserList',
  components: { Search, Operate, AddEdit },
  data() {
    return {
      name: '',
      height: 700,
      loading: false,
      idkey: 'user_id',
      query: {},
      data: [],
      count: 0,
      ids: [],
      addEditDialog: getAddEditDialog(),
      id: '',
      type: 'edit',
      dialog: false,
      dialogTitle: '',
      basedata: {
        exps: [],
        depts: [],
        posts: [],
        roles: [],
        deptProps: {
          value: 'dept_id',
          label: 'dept_name',
          checkStrictly: true,
          emitPath: false,
          multiple: true
        },
        postProps: {
          value: 'post_id',
          label: 'post_name',
          checkStrictly: true,
          emitPath: false,
          multiple: true
        },
        roleProps: {
          value: 'role_id',
          label: 'role_name',
          checkStrictly: true,
          emitPath: false,
          multiple: true
        }
      },
      permInfo: 'admin/system.User/info',
      permAdd: 'admin/system.User/add',
      permEdit: 'admin/system.User/edit',
      permDele: 'admin/system.User/dele',
      routeInfo: 'SystemUserInfo',
      routeAdd: 'SystemUserAdd',
      routeEdit: 'SystemUserEdit'
    }
  },
  created() {
    this.init()
  },
  methods: {
    hasPerm,
    init() {
      this.name = this.$t('用户')
      this.height = screenHeight()
      this.type = hasPerm([this.permEdit]) ? 'edit' : 'info'
      this.basedata.exps = [{ exp: 'like', name: this.$t('包含') }]
    },
    // 列表
    list() {
      this.loading = true
      listApi(this.query)
        .then((res) => {
          this.data = res.data.list
          this.count = res.data.count
          this.loading = false
          this.basedata.exps = res.data.basedata.exps
          this.basedata.depts = res.data.basedata.depts
          this.basedata.posts = res.data.basedata.posts
          this.basedata.roles = res.data.basedata.roles
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 查询
    search(query) {
      this.query = query
      this.list()
    },
    // 重置
    reset(query) {
      try {
        this.$refs['table'].clearSort()
      } catch (error) {}
      this.query = query
      this.list()
    },
    // 排序
    sort(sort) {
      this.query.sort_field = sort.column?.columnKey ?? sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
      } else if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
      }
      this.list()
    },
    // 选择
    select(rows) {
      this.ids = arrayColumn(rows, this.idkey)
    },
    // 添加
    add() {
      this.id = ''
      if (this.addEditDialog) {
        this.dialog = true
        this.dialogTitle = this.name + this.$t('添加')
      } else {
        this.$router.push({ name: this.routeAdd })
      }
    },
    // 修改
    async edit(row) {
      const route = this.type === 'edit' ? this.routeEdit : this.routeInfo
      const title = this.type === 'edit' ? this.$t('修改：') : this.$t('信息：')
      if (row) {
        this.id = row[this.idkey]
        if (this.addEditDialog) {
          this.dialog = true
          this.dialogTitle = this.name + title + this.id
        } else {
          this.$router.push({ name: route, params: { id: this.id } })
        }
      } else {
        const length = this.ids.length
        if (length) {
          if (this.addEditDialog) {
            this.id = this.ids[length - 1]
            this.dialog = true
            this.dialogTitle = this.name + title + this.id
          } else {
            for (let index = 0; index < length; index++) {
              await this.$router.push({ name: route, params: { id: this.ids[index] } })
            }
          }
        } else {
          ElMessageBox.alert(this.$t('请选择需要操作的', { name: this.name }), this.$t('提示'), {
            type: 'warning',
            center: true,
            callback: () => {}
          })
        }
      }
    },
    cancel() {
      this.dialog = false
      this.dialogTitle = ''
      this.id = ''
    },
    close() {
      this.cancel()
      this.list()
    },
    // 删除
    dele(row) {
      ElMessageBox.confirm(this.$t('确定要删除吗'), this.name + '：' + row[this.idkey], {
        type: 'warning',
        center: true
      })
        .then(() => {
          deleApi({ ids: [row[this.idkey]] })
            .then(() => {
              this.list()
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    deptSelect(node) {
      this.query.dept_id = node ? node.dept_id : null
      const dept_ids = node ? getChildIds(node, 'dept_id') : []
      this.query.dept_ids = dept_ids
      this.list()
    },
    postSelect(node) {
      this.query.post_id = node ? node.post_id : null
      const post_ids = node ? getChildIds(node, 'post_id') : []
      this.query.post_ids = post_ids
      this.list()
    },
    roleSelect(node) {
      this.query.role_id = node ? node.role_id : null
      const role_ids = node ? getChildIds(node, 'role_id') : []
      this.query.role_ids = role_ids
      this.list()
    }
  }
}
</script>
